package com.kaishengit.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.kaishengit.entity.User;

public class SessionFilter implements Filter{

	public void destroy() {
		
	}
	
	public boolean checkUrl(HttpServletRequest request) {
		
		String url = request.getRequestURI();
		url = url.substring(url.lastIndexOf("/")+1);
		String queryString = request.getQueryString();
		
		
		if("".equals(url.trim())) {
			return true;
		} else if("index.jsp".equals(url.trim())) {
			return true;
		} else if("user.jspx".equals(url.trim())) {
			if(queryString != null && !"".equals(queryString) && queryString.startsWith("_method=login")) {
				return true;
			} else {
				return false;
			}
		}
		return false;
	}
	
	

	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		//System.out.println("SessionFilter in");
		
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
	
		
		if(checkUrl(request)) {
			chain.doFilter(req, resp);
		} else {
			//session
			
			HttpSession session = request.getSession();
			User user = (User) session.getAttribute("CURRUSER");
			if(user != null) {
				chain.doFilter(req, resp);
			} else {
				response.sendRedirect("index.jsp?state=101");
			}
			
		}
		
		
		
		
		
		//chain.doFilter(req, resp);
		//System.out.println("SessionFilter out");
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

}
